package com.malty.apisdk.utils;

import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author malty
 */
public class SignUtil {
    public static String genQuerySign(Map<String, Object> hashMap, String secretKey) {
        Map<String, String> paramMap = hashMap.entrySet().stream()
                .filter(entry -> !ObjectUtils.isEmpty(entry.getKey()) &&
                        !ObjectUtils.isEmpty(entry.getValue()))
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> (String) entry.getValue(),
                        (oldValue, newValue) -> oldValue,
                        HashMap::new
                ));

        String sourceStr = new TreeMap<>(paramMap).entrySet().stream()
                .filter(e -> e.getKey() != null && !e.getKey().isEmpty())
                .filter(e -> e.getValue() != null && !e.getValue().isEmpty())
                .map(e -> e.getKey() + "=" + e.getValue())
                .collect(Collectors.joining("&"));

        String plaintext = String.format("%s_sign_%s", secretKey, sourceStr);
        System.out.println("签名原文：" + plaintext);
        return DigestUtils.md5DigestAsHex(plaintext.getBytes(StandardCharsets.UTF_8));
    }

}
